package com.jackrain.nea.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.core.webaction.WebAction;
import com.jackrain.nea.ext.permission.MenuNode;
import com.jackrain.nea.ext.permission.MenuType;
import com.jackrain.nea.ext.permission.Permissions;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.LimitQueue;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.model.MenuObject;
import com.jackrain.nea.web.model.UserConfig;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.query.QueryUtils;
import com.jackrain.nea.web.security.Security4Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;

import static com.jackrain.nea.ext.permission.TableMaskHelper.ALL_ACTION_PERMISSIONS;

/**
 * Created by Lucky dog on 2017/7/27.
 */
@Slf4j
@RestController
@Api(value = "MenuController", description = "顶部和侧边栏菜单接口")
public class MenuController {


    private static void doAdd(TableManager tm, JSONArray newParentNode, MenuNode node) {
        if (node == null) {
            return;
        }
        JSONObject newNode = doGetSingle(tm, node);
        if (newNode != null) {
            for (MenuNode childNode : node.getChildren()) {
                JSONArray children = (JSONArray) newNode.get("children");
                doAdd(tm, children, childNode);
            }
            newParentNode.add(newNode);
        }
    }

    private static JSONObject doGetSingle(TableManager tm, MenuNode node) {
        JSONObject result = new JSONObject();
        Long tmId = -1L;
        Object type = "";
        Object value = "";
        Object label = "";

        switch (node.getNodeType()) {
            case SUB_SYSTEM:
                tmId = node.getAd_subsystem_id();
                value = tmId;
                label = node.getName();
                type = "SubSystem";
                result.put("orignalType", "SubSystem");
                result.put("children", new JSONArray());
                break;
            case TABLE_CATEGORY:
                tmId = node.getAd_tablecategory_id();
                value = tmId;
                label = node.getName();
                type = "TableCategory";
                result.put("children", new JSONArray());
                result.put("orignalType", "TableCategory");
                break;
            case MENU:
                if (node.getType() == MenuType.TABLE) {
                    tmId = node.getAd_table_id();
                    value = node.getName();
                    label = node.getDescription();
                    type = "table";
                    result.put("orignalType", "table");
                    Table table = tm.getTable(tmId.intValue());
                    if (table == null) {
                        return null;
                    }
                    String url = table.getRowURL();
                    //void by yaoj table中的url是控制单对象界面跳转 与列表无关
//                    if (url != null && !url.isEmpty()) {
//                        type = "action";
//                    }
                    result.put("url", url);
                } else {
                    tmId = node.getAd_action_id();
                    value = node.getName();
                    label = node.getDescription();
                    type = "action";
                    result.put("orignalType", "action");
                    WebAction action = tm.getWebAction(tmId.intValue());
                    if(action != null){
                        String vueDisplay = action.getVuedisplay();
                        if(vueDisplay != null && !vueDisplay.isEmpty()){
                            result.put("vuedisplay", vueDisplay);
                        }
                    }
                    if (action == null || !action.getDisplayType().equals(WebAction.DisplayTypeEnum.Accord)) {
                        return null;
                    } else if (action.getActionType().equals(WebAction.ActionTypeEnum.URL)) {
                        //result.put("url", JSON.parseObject(action.getScript()));
                        result.put("url", action.getScript());
                    }
                }
                break;
            default:
        }
        result.put("id", tmId);
        result.put("value", value);
        result.put("label", label);
        result.put("type", type);
        result.put("menuId", node.getId());
        return result;
    }

    @ApiOperation(value = "获取切换菜单")
    @RequestMapping(path = "/p/cs/getSubSystems", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getSubSystems(HttpServletRequest request) {
//        User user = Security4Utils.getUser("root");
        User user = (UserImpl) request.getSession().getAttribute("user");
        ValueHolder vh = new ValueHolder();

        QuerySession session = QueryUtils.createQuerySession(user);
        TableManager tm = session.getTableManager();

        Collection<MenuNode> menus = Permissions.getMenusFilterByUser(session);

        try {
            JSONArray models = new JSONArray();
            for (MenuNode node : menus) {
                doAdd(tm, models, node);
            }
            vh.put("code", 0);
            vh.put("data", models);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            vh.put("code", -1);
            vh.put("message", e.getMessage());
        } finally {
            return vh.toJSONObject();
        }
    }

//    @ApiOperation(value = "获取表类别下Children")
//    @RequestMapping(path = "/p/cs/getTableCategoryChildren", method = {RequestMethod.GET, RequestMethod.POST})
//    public JSONObject getTableCategoryChildren(HttpServletRequest request,
//                                               @RequestParam(value = "tableCategory", required = true) int tableCategoryId) {
//        QuerySessionImpl querySession = new QuerySessionImpl(request);
//        ValueHolder vh = new ValueHolder();
//        try {
//            List lists = this.subSystemView.getChildrenOfTableCategory(request, tableCategoryId, true);
//            JSONArray children = new JSONArray();
//            for (Object o : lists) {
//                JSONObject jo = new JSONObject();
//                if (o instanceof Table) {
//                    jo.put("id", ((Table) o).getId());
//                    jo.put("value", ((Table) o).getName());
//                    jo.put("label", ((Table) o).getDescription(querySession.getLocale()));
//                    jo.put("type", "table");
//                } else if (o instanceof WebAction) {
//                    if (((WebAction) o).getDisplayType().equals(WebAction.DisplayTypeEnum.Accord)) {
//                        jo.put("id", ((WebAction) o).getId());
//                        jo.put("value", ((WebAction) o).getName());
//                        jo.put("label", ((WebAction) o).getDescription(querySession.getLocale()));
//                        jo.put("webaction", JSON.parseObject(((WebAction) o).getScript()));
//                        jo.put("type", "action");
//                    }
//                }
//                children.add(jo);
//            }
//            vh.put("code", 0);
//            vh.put("data", children);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            vh.put("code", -1);
//            vh.put("message", e.getMessage());
//        } finally {
//            return vh.toJSONObject();
//        }
//    }

    @ApiOperation(value = "获取店铺")
    @RequestMapping(path = "/p/cs/getStore", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getStore(HttpServletRequest request) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        int storeId = userWeb.getStoreId();
        JSONObject o = QueryEngine.getInstance().doQueryObject("select ID AS STOREID,STORENAME,IMAGE AS STOREIMAGE from C_STORE WHERE ID=?", new Object[]{storeId});
        vh.put("code", 0);
        vh.put("data", o);
        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取历史浏览和收藏夹")
    @RequestMapping(path = "/p/cs/getHistoryAndFavorite", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getHistoryAndFavorite(HttpServletRequest request) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySession session = new QuerySessionImpl(userWeb);

        RedisOpsUtil<String, LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        LimitQueue<MenuObject> queue = (LimitQueue<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("History", userWeb.getId().toString());
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite", userWeb.getId().toString());
        JSONObject jo = new JSONObject();

        if(queue == null){
            jo.put("history", new JSONArray());
        }else{
            int cnt = queue.size();
            LimitQueue<MenuObject> history = new LimitQueue<>(10);
            for(int i=0; i<cnt; i++){
                MenuObject o = queue.poll();
                if("table".equals(o.getType())){
                    if(Permissions.hasPermission(session,MenuType.TABLE,Long.valueOf(o.getId()), Security4Utils.PREMEnum.READ.getPrem())){
                        history.offer(o);
                    }
                }else{
                    if(Permissions.hasPermission(session,MenuType.ACTION,Long.valueOf(o.getId()),ALL_ACTION_PERMISSIONS)){
                        history.offer(o);
                    }
                }
            }
            redisOpsUtil.objRedisTemplate.opsForHash().put("History", userWeb.getId().toString(), history);
            jo.put("history", history);
        }

        if(list == null){
            jo.put("favorite", new JSONArray());
        }else{
            ArrayList<MenuObject> favorite = new ArrayList<>();
            for(int i=0; i<list.size(); i++){
                MenuObject o = list.get(i);
                if("table".equals(o.getType())){
                    if(Permissions.hasPermission(session,MenuType.TABLE,Long.valueOf(o.getId()),Security4Utils.PREMEnum.READ.getPrem())){
                        favorite.add(o);
                    }
                }else{
                    if(Permissions.hasPermission(session,MenuType.ACTION,Long.valueOf(o.getId()),ALL_ACTION_PERMISSIONS)){
                        favorite.add(o);
                    }
                }
            }
            redisOpsUtil.objRedisTemplate.opsForHash().put("Favorite", userWeb.getId().toString(), favorite);
            jo.put("favorite", favorite);
        }
        vh.put("code", 0);
        vh.put("data", jo);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "记住历史浏览")
    @RequestMapping(path = "/p/cs/recHistory", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject recHistory(HttpServletRequest request,
                                 @RequestParam(value = "url") String url,
                                 @RequestParam(value = "type") String type,
                                 @RequestParam(value = "id") int id) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if (type.equals("table")) {
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setLabel(((Table) o).getDescription(querySession.getLocale()));
            menuObject.setUrl(url);
        } else if (type.equals("action")) {
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(((WebAction) o).getScript());
            menuObject.setUrl(url);
        }
        if (menuObject == null) {
            vh.put("code", -1);
            vh.put("message", "Object cannot be found in schema");
            return vh.toJSONObject();
        }
        RedisOpsUtil<String, LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        LimitQueue<MenuObject> queue = (LimitQueue<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("History", userWeb.getId().toString());
        if (queue == null) {
            queue = new LimitQueue<MenuObject>(10);
            queue.offer(menuObject);
        } else {
            queue.remove(menuObject);
            queue.offer(menuObject);
        }
        redisOpsUtil.objRedisTemplate.opsForHash().put("History", userWeb.getId().toString(), queue);
        HashMap map = new HashMap();
        map.put("command","com.jackrain.nea.cp.api.CuserLogSaveCmd:1.0:cp");
        map.put("menuname",menuObject.getLabel());
        map.put("user",userWeb);
        sendMsg(map,"RecHistory");

        vh.put("code", 0);
        vh.put("data", queue);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "添加收藏")
    @RequestMapping(path = "/p/cs/addToFavorite", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject addToFavorite(HttpServletRequest request,
                                    @RequestParam(value = "url") String url,
                                    @RequestParam(value = "type") String type,
                                    @RequestParam(value = "id") int id) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if (type.equals("table")) {
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setLabel(((Table) o).getDescription(querySession.getLocale()));
            menuObject.setUrl(url);
        } else if (type.equals("action")) {
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(((WebAction) o).getScript());
            menuObject.setUrl(url);
        }

        if (menuObject == null) {
            vh.put("code", -1);
            vh.put("message", "Object cannot be found in schema");
            return vh.toJSONObject();
        }

        RedisOpsUtil<String, ArrayList<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite", userWeb.getId().toString());
        if (list == null) {
            list = new ArrayList<MenuObject>();
        }
        if (!list.contains(menuObject)) {
            list.add(menuObject);
            redisOpsUtil.objRedisTemplate.opsForHash().put("Favorite", userWeb.getId().toString(), list);
        }

        vh.put("code", 0);
        vh.put("data", list);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "取消收藏")
    @RequestMapping(path = "/p/cs/removeFromFavorite", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject removeFromFavorite(HttpServletRequest request,
                                         @RequestParam(value = "type", required = true) String type,
                                         @RequestParam(value = "id", required = true) int id) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if (type.equals("table")) {
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setValue(((Table) o).getDescription(querySession.getLocale()));
        } else if (type.equals("action")) {
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(((WebAction) o).getScript());
        }

        RedisOpsUtil<String, LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite", userWeb.getId().toString());

        list.remove(menuObject);
        redisOpsUtil.objRedisTemplate.opsForHash().put("Favorite", userWeb.getId().toString(), list);

        vh.put("code", 0);
        vh.put("data", list);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取消息通知")
    @RequestMapping(path = "/p/cs/getUNote", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getUNote(HttpServletRequest request) {

        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        String sql = "SELECT  ID,TITLE,PRIORITYRULE,MODIFIEDDATE,DESCRIPTION FROM U_NOTE\n" +
                "WHERE DOCSTATUS='INIT' AND USER_ID=? ORDER BY MODIFIEDDATE LIMIT 0,5";

        JSONArray ja = QueryEngine.getInstance().doQueryObjectArray(sql, new Object[]{userWeb.getId()});


        vh.put("code", 0);
        vh.put("data", ja);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "更改消息通知")
    @RequestMapping(path = "/p/cs/markReadUNote", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject markReadUNote(HttpServletRequest request, @RequestParam(value = "id", required = true) long id) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        String sql = "UPDATE U_NOTE SET DOCSTATUS='READ',MODIFIEDDATE=NOW(),MODIFIERID=? WHERE ID=?";
        QueryEngine.getInstance().executeUpdate(sql, new Object[]{userWeb.getId(), id});
        vh.put("code", 0);
        vh.put("message", "success");

        return vh.toJSONObject();
    }

    @ApiOperation(value = "设置列表隐藏字段")
    @RequestMapping(path = "/p/cs/setHideColumn", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject setHideColumn(HttpServletRequest request,
                                    @RequestParam(value = "tableid", required = true) long tableId,
                                    @RequestParam(value = "hidecolumns", required = true) String hideColumn) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.addHideColumn(tableId, hideColumn);
        redisOpsUtil.objRedisTemplate.opsForHash().put("UserConfig", userWeb.getId().toString(), userConfig);

        vh.put("code", 0);
        vh.put("data", hideColumn);

        return vh.toJSONObject();
    }


    @ApiOperation(value = "保存多选结果集条件")
    @RequestMapping(path = "/p/cs/setMultiQuery", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject setMultiQuery(HttpServletRequest request,
                                    @RequestParam(value = "tableid", required = true) long tableid,
                                    @RequestParam(value = "modelname", required = true) String modelname,
                                    @RequestParam(value = "multiQuery", required = true) String multiQuery) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.addMultiQuery(tableid, modelname, multiQuery);
        redisOpsUtil.objRedisTemplate.opsForHash().put("UserConfig", userWeb.getId().toString(), userConfig);

        vh.put("code", 0);
        vh.put("data", multiQuery);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "删除多选结果集条件")
    @RequestMapping(path = "/p/cs/delMultiQuery", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject delMultiQuery(HttpServletRequest request,
                                    @RequestParam(value = "tableid", required = true) long tableid,
                                    @RequestParam(value = "modelname", required = true) String modelname) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.delMultiQuery(tableid, modelname);
        redisOpsUtil.objRedisTemplate.opsForHash().put("UserConfig", userWeb.getId().toString(), userConfig);

        vh.put("code", 0);
        vh.put("data", modelname);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取UserConfig")
    @RequestMapping(path = "/p/cs/getUserConfig", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getUserConfig(HttpServletRequest request,
                                    @RequestParam(value = "type", required = true) String type,
                                    @RequestParam(value = "id", required = true) int id) {

        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        RedisOpsUtil<String, LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);

        //收藏夹
        MenuObject menuObject = new MenuObject();
        menuObject.setId(id);
        menuObject.setType(type);
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite", userWeb.getId().toString());

        //用户设置
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());
        String hideColumn = null;
        Boolean isFoldCond = null;

        if(userConfig == null || userConfig.getHideColumn(new Long(id)) == null){
            hideColumn = "";
        } else {
            hideColumn = userConfig.getHideColumn(new Long(id));
        }

        if(userConfig == null || userConfig.getParam("isFoldCond") == null){
            isFoldCond = false;
        } else {
            isFoldCond = Boolean.parseBoolean(userConfig.getParam("isFoldCond"));
        }


        JSONObject jo = new JSONObject();
        jo.put("hideColumn",hideColumn);
        jo.put("isFoldCond", isFoldCond);
        jo.put("isFavorite", list == null? false : list.contains(menuObject));

        vh.put("code", 0);
        vh.put("data", jo);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取MultiQuery")
    @RequestMapping(path = "/p/cs/getMultiQuery", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getMultiQuery(HttpServletRequest request,
                                    @RequestParam(value = "tableid", required = true) long tableid) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());

        JSONArray ja = new JSONArray();
        if (userConfig != null) {
            HashMap<String, String> map = userConfig.getMultiQueryByTable(tableid);
            if(map != null && map.size() > 0){
                for (String key : map.keySet()) {
                    JSONObject tmp = new JSONObject();
                    tmp.put("key", key);
                    tmp.put("value", map.get(key));
                    ja.add(tmp);
                }
            }

        }

        vh.put("code", 0);
        vh.put("data", ja);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "设置列用户参数")
    @RequestMapping(path = "/p/cs/setUserParam", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject setUserParam(HttpServletRequest request,
                                    @RequestParam(value = "name", required = true) String name,
                                    @RequestParam(value = "value", required = true) String value) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.addParam(name, value);
        redisOpsUtil.objRedisTemplate.opsForHash().put("UserConfig", userWeb.getId().toString(), userConfig);
        vh.put("code", 0);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取用户参数列表")
    @RequestMapping(path = "/p/cs/getParamList", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getParamList(HttpServletRequest request) {
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        //User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String, UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig", userWeb.getId().toString());

        JSONArray ja = new JSONArray();
        if (userConfig != null) {
            HashMap<String, String> map = userConfig.getParam();
            if(map != null && map.size() > 0){
                for (String key : map.keySet()) {
                    JSONObject tmp = new JSONObject();
                    tmp.put("name", key);
                    tmp.put("value", map.get(key));
                    ja.add(tmp);
                }
            }

        }

        vh.put("code", 0);
        vh.put("data", ja);

        return vh.toJSONObject();
    }


    private void sendMsg(HashMap map,String tag) {
        log.debug("map->" + map);
        try{
            ProducerBean producerBean = (ProducerBean) ApplicationContextHandle.getBean(ProducerBean.class);
            PropertiesConf pconf = (PropertiesConf) ApplicationContextHandle.getBean("propertiesConf");
            String topic = pconf.getProperty("ons.mq.topic2");
            Message msg = null;
            msg = new Message(topic, tag, MsgConvertUtil
                    .objectSerialize(map));
            msg.setKey(UUID.randomUUID().toString());
            SendResult sendResult = producerBean.send(msg);
            if (sendResult != null) {
                log.debug("handleaspect sendMsg success tag-:" + tag + " topic:" + topic + " sendResult msgid:" + sendResult.getMessageId());
            } else {
                log.error("handleaspect sendMsg success tag-:" + tag + " topic:" + topic + " send error");
            }
        }catch(Exception e){
            log.error(e.getMessage(),e);
        }

    }


}
